/*
 * $Id: $
 */
package org.rcgwt.client.ui.grid.event;

import com.google.gwt.event.shared.GwtEvent;

/**
 * 
 * @author Olivier Oeuillot (latest modification by $Author: $)
 * @version $Revision: $ $Date: $
 */
public class CheckEvent<I> extends GwtEvent<CheckHandler<I>> {

    /**
     * Handler type.
     */
    private static Type<CheckHandler< ? >> TYPE;

    /**
     * Fires a selection event on all registered handlers in the handler
     * manager.If no such handlers exist, this method will do nothing.
     * 
     * @param <I>
     *            the selected item type
     * @param source
     *            the source of the handlers
     * @param selectedItem
     *            the selected item
     */
    public static <I> void fire(HasCheckHandlers<I> source, I selectedItem) {
        if (TYPE != null) {
            CheckEvent<I> event = new CheckEvent<I>(selectedItem);
            source.fireEvent(event);
        }
    }

    /**
     * Gets the type associated with this event.
     * 
     * @return returns the handler type
     */
    public static Type<CheckHandler< ? >> getType() {
        if (TYPE == null) {
            TYPE = new Type<CheckHandler< ? >>();
        }
        return TYPE;
    }

    private final I checkedItem;

    /**
     * Creates a new selection event.
     * 
     * @param selectedItem
     *            selected item
     */
    protected CheckEvent(I selectedItem) {
        this.checkedItem = selectedItem;
    }

    // The instance knows its BeforeSelectionHandler is of type I, but the TYPE
    // field itself does not, so we have to do an unsafe cast here.
    @SuppressWarnings("unchecked")
    @Override
    public final Type<CheckHandler<I>> getAssociatedType() {
        return (Type) TYPE;
    }

    /**
     * Gets the selected item.
     * 
     * @return the selected item
     */
    public I getCheckedItem() {
        return checkedItem;
    }

    @Override
    protected void dispatch(CheckHandler<I> handler) {
        handler.onCheck(this);
    }
}
